package com.quanshu.exchange.ui.gui.message.mass_send;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baselibrary.util.glide.GlideUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.chat.ChatConstant;
import com.quanshu.exchange.support.db.UserDao;
import com.quanshu.exchange.support.entity.GroupEntity;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.entity.tmp.TmpDestChatUser;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.CheckUtil;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;
import com.quanshu.exchange.ui.gui.profile.DialogPhotoSelect;
import com.quanshu.exchange.ui.widget.LoadingDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 群发消息
 * Created by xiniu003 on 2017/12/11.
 */

public class MassMessageActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.comment_mass_message)
    LinearLayout commentMassMessage;
    @BindView(R.id.mass_message_content)
    EditText massMessageContent;
    @BindView(R.id.message_length)
    TextView messageLength;
    @BindView(R.id.send_user_rel)
    RelativeLayout sendUserRel;
    @BindView(R.id.send_member_quantity)
    TextView sendMemberQuantity;
    @BindView(R.id.send_member_list)
    RecyclerView recyclerView;
    @BindView(R.id.image_msg)
    ImageView imageMsg;
    @BindView(R.id.image_msg_dot)
    ImageView imageMsgDot;
    @BindView(R.id.image_msg_layout)
    RelativeLayout imageMsgLayout;
    @BindView(R.id.image_msg_add)
    ImageView imageMsgAdd;

    private List<TmpDestChatUser> chatUsers = new ArrayList<>();
    private SingleAdapter<TmpDestChatUser> adapter;
    private List<UserEntity> beSelectedUser;
    private List<GroupEntity> beSelectGroup;
    private HashMap<String, List<String>> beSelectedLabel;

    private String text;
    private String imagePath;
    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mass_message);
        ButterKnife.bind(this);
        initView();
        initListener();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            if (what == 1) {
                if (loadingDialog != null) {
                    ToastHelper.toast("发送成功");
                    loadingDialog.dismiss();
                    finish();
                }
            }
        }
    };

    private void initView() {
        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        adapter = new SingleAdapter<>(new DataDisplayer<TmpDestChatUser>(this, R.layout.item_image_with_title) {
            @Override
            public void bindData(BaseViewHolder holder, LayoutWrapper<TmpDestChatUser> wrapper, TmpDestChatUser item, int position) {
                // 如果是好友
                if (item.getFlag() == 0) {
                    holder.setRoundImageUrl(R.id.item_image_imageView, item.getAvatar(), R.drawable.default_avatar);
                }
                // 是群
                else {
                    holder.setRoundImageUrl(R.id.item_image_imageView, item.getAvatar(), R.drawable.default_group_avatar);
                }
                holder.setText(R.id.item_image_title, item.getTitle());
            }
        });
        recyclerView.setAdapter(adapter);
    }

    private void initListener() {
        RxViewHelper.getInstance().clicks(back, aVoid -> finish());
        RxViewHelper.getInstance().clicks(sendUserRel, aVoid -> goAddMemberActivity());
        RxViewHelper.getInstance().clicks(commentMassMessage, aVoid -> doSend());
        RxViewHelper.getInstance().afterTextChangeEvents(massMessageContent,
                textViewAfterTextChangeEvent -> {
                    text = textViewAfterTextChangeEvent.editable().toString();
                    if (text != null && text.length() > 0) {
                        messageLength.setText(massMessageContent.length() + "/200");
                    } else {
                        messageLength.setText("0" + "/200");
                    }
                });

        RxViewHelper.getInstance().clicks(imageMsgAdd, aVoid -> doShowPhotoDialog());
        RxViewHelper.getInstance().clicks(imageMsgDot, aVoid -> doClearMsgImage());
    }

    private void doClearMsgImage() {
        imagePath = null;
        imageMsg.setBackground(null);
        imageMsg.setImageDrawable(null);
        imageMsgLayout.setVisibility(View.GONE);
        imageMsgAdd.setVisibility(View.VISIBLE);
    }

    private void goAddMemberActivity() {
        Intent intent = new Intent(MassMessageActivity.this, AddMemberActivity.class);
        if (CheckUtil.isValidate(beSelectGroup)) {
            intent.putExtra("List<GroupEntity>", (Serializable) beSelectGroup);
        }
        if (CheckUtil.isValidate(beSelectGroup)) {
            intent.putExtra("List<UserEntity>", (Serializable) beSelectedUser);
        }
        if (CheckUtil.isValidate(beSelectedLabel)) {
            intent.putExtra("HashMap<String, List<String>>", beSelectedLabel);
        }
        startActivityForResult(intent, 0x01);
    }

    private void doSend() {
        if (chatUsers == null || chatUsers.size() < 1) {
            ToastHelper.toast("还未选择发送对象");
            return;
        }
        if ((text == null || text.trim().length() < 1) && (imagePath == null || imagePath.trim().length() < 1)) {
            ToastHelper.toast("消息为空");
            return;
        }
        loadingDialog = new LoadingDialog(this, false);
        loadingDialog.show();
        for (TmpDestChatUser chatUser : chatUsers) {
            // 发送文字消息
            if (text != null && text.trim().length() > 0) {
                doSendTextMessage(text, chatUser);
            }
            if (imagePath != null && imagePath.trim().length() > 0) {
                sendImageMessage(imagePath, chatUser);
            }
            handler.sendEmptyMessageDelayed(1, 5000);
        }
    }

    private void doSendTextMessage(String str, TmpDestChatUser chatUser) {
        if (TextUtils.isEmpty(str)) {
            ToastHelper.toast("不能发送空消息");
            return;
        }
        EMMessage message = EMMessage.createTxtSendMessage(str, chatUser.getDestId());
        sendMsg(message, chatUser);
    }

    protected void sendImageMessage(String imagePath, TmpDestChatUser chatUser) {
        EMMessage message = EMMessage.createImageSendMessage(imagePath, true, chatUser.getDestId());
        sendMsg(message, chatUser);
    }

    private void sendMsg(EMMessage message, TmpDestChatUser chatUser) {
        // 私聊
        if (chatUser.getFlag() == 0) {
            message.setChatType(EMMessage.ChatType.Chat);
        }
        // 群聊
        else if (chatUser.getFlag() == 1) {
            message.setChatType(EMMessage.ChatType.GroupChat);
            message.setAttribute(ChatConstant.Chat_group_id, chatUser.getDestId());
            message.setAttribute(ChatConstant.Chat_group_photo, chatUser.getAvatar());
            message.setAttribute(ChatConstant.Chat_group_name, chatUser.getTitle());
            message.setAttribute(ChatConstant.Chat_group_owner, chatUser.getGroupOwner());
//            if (chatUser.getRelation_type() == 2) {
//                message.setAttribute(ChatConstant.Chat_relation_type, "true");
//            } else {
//                message.setAttribute(ChatConstant.Chat_relation_type, "false");
//            }
        }
        message.setAttribute(ChatConstant.Chat_send_member_id, currentUser.getMemberid());
        message.setAttribute(ChatConstant.Chat_ext_attr_photo, currentUser.getAvatar());
        message.setAttribute(ChatConstant.Chat_ext_attr_nickname, currentUser.getNickname());
        EMClient.getInstance().chatManager().saveMessage(message);
        EMClient.getInstance().chatManager().sendMessage(message);

        // 是不是公开群
        if (chatUser.getVisible() == 1) {
            message.setAttribute(ChatConstant.Chat_ext_attr_is_toAll, true);
        } else {
            message.setAttribute(ChatConstant.Chat_ext_attr_is_toAll, false);
        }
    }

    private void doShowPhotoDialog() {
        DialogPhotoSelect dialogPhotoSelect = new DialogPhotoSelect(this);
        dialogPhotoSelect.show();
        dialogPhotoSelect.getAlbumSubject().subscribe(o -> {
            PictureSelector.create(this)
                    .openGallery(PictureMimeType.ofImage())
                    .selectionMode(PictureConfig.SINGLE)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
            dialogPhotoSelect.cancel();
        });
        dialogPhotoSelect.getTakePhotoSubject().subscribe(o -> {
            PictureSelector.create(this)
                    .openCamera(PictureMimeType.ofImage())
                    .selectionMode(PictureConfig.SINGLE)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
            dialogPhotoSelect.cancel();
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0x01) {
                beSelectedUser = (List<UserEntity>) data.getSerializableExtra("List<UserEntity>");
                if (CheckUtil.isValidate(beSelectedUser)) {
                    for (UserEntity userEntity : beSelectedUser) {
                        TmpDestChatUser chatUser = new TmpDestChatUser();
                        chatUser.setDestId(userEntity.getMemberid());
                        chatUser.setAvatar(userEntity.getAvatar());
                        chatUser.setFlag(0);
                        chatUser.setTitle(AppUtils.getUserName(userEntity));
                        chatUsers.add(chatUser);
                    }
                }
                beSelectGroup = (List<GroupEntity>) data.getSerializableExtra("List<GroupEntity>");
                if (CheckUtil.isValidate(beSelectGroup)) {
                    for (GroupEntity groupEntity : beSelectGroup) {
                        TmpDestChatUser chatUser = new TmpDestChatUser();
                        chatUser.setDestId(groupEntity.getHx_groupid());
                        chatUser.setAvatar(groupEntity.getGroup_photo());
                        chatUser.setGroupOwner(groupEntity.getOwner());
                        chatUser.setFlag(1);
                        chatUser.setVisible(groupEntity.getVisible());
                        chatUser.setRelation_type(groupEntity.getRelation_type());
                        chatUser.setTitle(groupEntity.getGroup_name());
                        chatUsers.add(chatUser);
                    }
                }
                beSelectedLabel = (HashMap<String, List<String>>) data.getSerializableExtra("HashMap<String, List<String>>");
                if (CheckUtil.isValidate(beSelectedLabel)) {
                    List<String> memberIds = new ArrayList<>();
                    List<UserEntity> userEntityList = UserDao.getInstance().queryForAll();
                    if (CheckUtil.isValidate(userEntityList)) {
                        Set keys = beSelectedLabel.keySet();
                        if (keys != null) {
                            Iterator iterator = keys.iterator();
                            while (iterator.hasNext()) {
                                String key = (String) iterator.next();
                                memberIds.addAll(beSelectedLabel.get(key));
                            }
                        }
                        if (CheckUtil.isValidate(memberIds)) {
                            for (String id : memberIds) {
                                for (UserEntity userEntity : userEntityList) {
                                    if (id.equals(userEntity.getMemberid())) {
                                        TmpDestChatUser chatUser = new TmpDestChatUser();
                                        chatUser.setDestId(userEntity.getMemberid());
                                        chatUser.setAvatar(userEntity.getAvatar());
                                        chatUser.setFlag(0);
                                        chatUser.setTitle(AppUtils.getUserName(userEntity));
                                        chatUsers.add(chatUser);
                                    }
                                }
                            }
                        }
                    }
                }
                if (chatUsers != null && adapter != null) {
                    adapter.setData(chatUsers);
                    sendMemberQuantity.setText("共 " + chatUsers.size() + " 人");
                }
            } else if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                imagePath = selectList.get(0).getPath();
                GlideUtils.setRoundImageView(this, imagePath, R.drawable.default_img, imageMsg);
                imageMsgLayout.setVisibility(View.VISIBLE);
                imageMsgAdd.setVisibility(View.GONE);

            }

        }
    }

}
